<?PHP

include 'dbconnect.php';
include 'sql.php';

$userName = "";
$password = "";
$errorMessage = "";

if ($_SERVER['REQUEST_METHOD'] == 'POST'){
	
	$userName = $_POST['username'];
	$password = $_POST['password'];

	$userName = htmlspecialchars($userName);
	$password = htmlspecialchars($password);
	
	//==========================================
	//	CONNECT TO THE LOCAL DATABASE
	//==========================================
	
	$db_handle = connect_to_sql();
	$db_found = connect_to_db($db_handle);

	if ($db_found) {

		$userName = quote_smart($userName, $db_handle);
		$password = quote_smart($password, $db_handle);

		$result = getBasicUserInfo($userName, $password);
		
	//====================================================
	//	CHECK TO SEE IF THE $result VARIABLE IS TRUE
	//====================================================
		if ($result) {
			$num_rows = mysql_num_rows($result);
			if ($num_rows > 0) {
				session_start();
				$_SESSION['login'] = "1";

				if($result === FALSE) {
					die(mysql_error()); // TODO: better error handling
				}

				while($row = mysql_fetch_array($result))
				{
					$_SESSION['firstName'] = $row['firstname'];
					$_SESSION['middleName'] = $row['middlename'];
					$_SESSION['lastName'] = $row['lastname'];
					$_SESSION['userName'] = $row['username'];
					$_SESSION['nwlID'] = $row['nwlID'];
					$_SESSION['isActive'] = $row['isActive'];
                    $_SESSION['userID'] = $row['userID'];
					
				}
				header ("Location: index.php");
				
			}
			else {
				session_start();
				$_SESSION['login'] = "";
				header ("Location: login.php");
			}	
		}
		else {
			$errorMessage = "Error logging on";
		}

	mysql_close($db_handle);

	}

	else {
		$errorMessage = "Error logging on";
	}

}


?>

<!DOCTYPE html>
<html>
<head>
<title>Basic Login Script</title>
</head>
<body>

<FORM NAME ="form1" METHOD ="POST" ACTION ="login.php">

Username: <INPUT TYPE = 'TEXT' Name ='username'  value="<?PHP print $userName;?>" maxlength="20">
Password: <INPUT TYPE = 'TEXT' Name ='password'  value="<?PHP print $password;?>" maxlength="16">

<P align = center>
<INPUT TYPE = "Submit" Name = "Submit1"  VALUE = "Login">
</P>

</FORM>

<P>
</body>
</html>